package com.sky.service.impl;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.mapper.WorkSpaceMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.BusinessDataVO;
import com.sky.vo.DishOverViewVO;
import com.sky.vo.OrderOverViewVO;
import com.sky.vo.SetmealOverViewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WorkSpaceServiceImpl implements WorkSpaceService {

    @Autowired
    private WorkSpaceMapper workSpaceMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 查询今日运营数据
     * @return
     */
    @Transactional
    public BusinessDataVO businessData() {
        BusinessDataVO businessDataVO = new BusinessDataVO();
        LocalDate today = LocalDate.now();
        Integer newUser =  workSpaceMapper.todayNewUser(today);
        List<Orders> ordersList = workSpaceMapper.todayOrdersList(today);
        Integer validOrderCount = 0;
        Integer totalOrderCount = 0;
        BigDecimal turnover = BigDecimal.valueOf(0.0);

        for (Orders orders : ordersList) {
            if(orders.getStatus() == Orders.COMPLETED)
            {
                validOrderCount++;
            }
            turnover =  turnover.add(orders.getAmount());
            totalOrderCount++;
        }

        // 计算单价（需处理除零）
        double unitPrice = 0.0;
        if (totalOrderCount > 0) {
            unitPrice = turnover.doubleValue() / totalOrderCount;
        }
        // 计算订单完成率（同样需处理除零）
        double orderCompletionRate = 0.0;
        if (totalOrderCount > 0) {
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }
        businessDataVO.setNewUsers(newUser);
        businessDataVO.setTurnover(turnover.doubleValue());
        businessDataVO.setUnitPrice(unitPrice);
        businessDataVO.setValidOrderCount(validOrderCount);
        businessDataVO.setOrderCompletionRate(orderCompletionRate);

        return businessDataVO;
    }

    /**
     * 查询总共套餐总览
     * @return
     */
    public SetmealOverViewVO overViewSetMeals() {
        SetmealOverViewVO setmealOverViewVO =  workSpaceMapper.setMealOverView();
        return setmealOverViewVO;
    }

    /**
     * 查询总共菜品总览
     * @return
     */
    public DishOverViewVO overViewDishes() {
        DishOverViewVO dishOverViewVO =  workSpaceMapper.dishesOverView();
        return dishOverViewVO;
    }

    /**
     * 查询总共订单总览
     * @return
     */
    public OrderOverViewVO overViewOrders() {
        OrderOverViewVO orderOverViewVO = workSpaceMapper.ordersOverView();
        return orderOverViewVO;
    }


    /**
     * 根据时间段统计营业数据
     * @param begin
     * @param end
     * @return
     */
    public BusinessDataVO getBusinessData(LocalDateTime begin, LocalDateTime end) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        Map map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);

        //查询总订单数
        Integer totalOrderCount = orderMapper.countByMap(map);

        map.put("status", Orders.COMPLETED);
        //营业额
        Double turnover = orderMapper.sumByMap(map);
        turnover = turnover == null? 0.0 : turnover;

        //有效订单数
        Integer validOrderCount = orderMapper.countByMap(map);

        Double unitPrice = 0.0;

        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0 && validOrderCount != 0){
            //订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
            //平均客单价
            unitPrice = turnover / validOrderCount;
        }

        //新增用户数
        Integer newUsers = userMapper.countByMap(map);

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }

}
